Spring MVC 4 常用注解汇总

最近在用Spring boot做REST风格接口的新架构,由于已经快2年没有大规模使用Spring MVC了,发现很多新的注解都没有用过,因此花了点时间学习和汇总,Spring MVC现在功能还是很强大的。 通过大量使用注解可以简化REST接口的开发。
  Spring从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping, @RequestParam, @ModelAttribute等等这样类似的注解。到目前为止,Spring的版本虽然发生了很大的变化,但注解的特性却是一直延续下来,并不断扩展,让广大的开发人员的双手变的更轻松起来,这都离不开Annotation的强大作用,今天我们就一起来看看Spring

MVC 4中常用的那些注解吧。

1. @Controller

Controller控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后将试图呈献给用户。Spring MVC 使用 @Controller 定义控制器,它还允许自动检测定义在类路径下的组件并自动注册。如想自动检测生效,需在XML头文件下引入

spring-context:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="org.springframework.samples.petclinic.web"/>

<!-- ... --></beans>

2. @RequestMapping

我们可以 @RequestMapping 注解将类似 “/favsoft”这样的URL映射到整个类或特定的处理方法上。一般来说,类级别的注解映射特定的请求路径到表单控制器上,而方法级别的注解只是映射为一个特定的HTTP方法请求(“GET”,“POST”等)或HTTP请求参数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Controller
@RequestMapping("/favsoft")
public class AnnotationController {

@RequestMapping(method=RequestMethod.GET)
public String get(){
return "";
}

@RequestMapping(value="/getName", method = RequestMethod.GET)
public String getName(String userName) {
return userName;
}

@RequestMapping(value="/{day}", method=RequestMethod.GET)
public String getDay(Date day){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(day);
}

@RequestMapping(value="/addUser", method=RequestMethod.GET)
public String addFavUser(@Validated FavUser favUser,BindingResult result){
if(result.hasErrors()){
return "favUser";
}
//favUserService.addFavUser(favUser);
return "redirect:/favlist";
}

@RequestMapping("/test")
@ResponseBody
public String test(){
return "aa";
}

}
@RequestMapping 既可以作用在类级别,也可以作用在方法级别。当它定义在类级别时,标明该控制器处理所有的请求都被映射到 /favsoft 路径下。@RequestMapping中可以使用 method 属性标记其所接受的方法类型,如果不指定方法类型的话,可以使用 HTTP GET/POST 方法请求数据,但是一旦指定方法类型,就只能使用该类型获取数据。

@RequestMapping 可以使用 @Validated与BindingResult联合验证输入的参数,在验证通过和失败的情况下,分别返回不同的视图。

@RequestMapping支持使用URI模板访问URL。URI模板像是URL模样的字符串,由一个或多个变量名字组成,当这些变量有值的时候,它就变成了URI。

3. @PathVariable

在Spring MVC中,可以使用 @PathVariable 注解方法参数并将其绑定到URI模板变量的值上。如下代码所示:
1
2
3
4
5
 String findOwner( String , Model model) {
FavUser favUser = favUserService.findFavUser();
model.addAttribute(
;
}

URI模板 “favusers/{favUserId}”指定变量的名字 favUserId ,当控制器处理这个请求的时候, favUserId的值会被设定到URI中。比如,当有一个像“favusers/favccxx”这样的请求时,favUserId的值就是 favccxx。

@PathVariable 可以有多个注解,像下面这样:


1
2
3
4
5
@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
Pet pet = owner.getPet(petId);
model.addAttribute("pet", pet); return "displayPet";
}
@PathVariable中的参数可以是任意的简单类型,如int, long, Date等等。Spring会自动将其转换成合适的类型或者抛出 TypeMismatchException异常。当然,我们也可以注册支持额外的数据类型。 如果@PathVariable使用Map<String, String>类型的参数时, Map会填充到所有的URI模板变量中。 @PathVariable支持使用正则表达式,这就决定了它的超强大属性,它能在路径模板中使用占位符,可以设定特定的前缀匹配,后缀匹配等自定义格式。 @PathVariable还支持矩阵变量,因为现实场景中用的不多,这就不详细介绍了,有需要的童鞋请查看官网的文档。 4. @RequestParam @RequestParam将请求的参数绑定到方法中的参数上,如下面的代码所示。其实,即使不配置该参数,注解也会默认使用该参数。如果想自定义指定参数的话,如果将@RequestParam的 required 属性设置为false(如@RequestParam(value="id",required=false))。 5. @RequestBody @RequestBody是指方法参数应该被绑定到HTTP请求Body上。 @RequestMapping(value = "/something", method = RequestMethod.PUT)public void handle(@RequestBody String body, Writer writer) throws IOException { writer.write(body); }

如果觉得@RequestBody不如@RequestParam趁手,我们可以使用 HttpMessageConverter将request的body转移到方法参数上, HttMessageConverser将 HTTP请求消息在Object对象之间互相转换,但一般情况下不会这么做。事实证明,@RequestBody在构建REST架构时,比@RequestParam有着更大的优势。

  1. @ResponseBody

    @ResponseBody与@RequestBody类似,它的作用是将返回类型直接输入到HTTP response body中。@ResponseBody在输出JSON格式的数据时,会经常用到,代码见下图:

    @RequestMapping(value = “/something”, method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() { return “Hello World”;
    }

    1. @RestController

    我们经常见到一些控制器实现了REST的API,只为服务于JSON,XML或其它自定义的类型内容,@RestController用来创建REST类型的控制器,与@Controller类型。@RestController就是这样一种类型,它避免了你重复的写@RequestMapping与@ResponseBody。

1
2
3
4
5
6
7
8
@RestController
public class FavRestfulController {

@RequestMapping(value="/getUserName",method=RequestMethod.POST)
public String getUserName(@RequestParam(value="name") String name){
return name;
}
}

8. HttpEntity

HttpEntity除了能获得request请求和response响应之外,它还能访问请求和响应头,如下所示:
1
2
3
4
5
6
@RequestMapping("/something")public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader")); byte[] requestBody = requestEntity.getBody(); // do something with request header and body

HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

9. @ModelAttribute

@ModelAttribute可以作用在方法或方法参数上,当它作用在方法上时,标明该方法的目的是添加一个或多个模型属性(model attributes)。该方法支持与@RequestMapping一样的参数类型,但并不能直接映射成请求。控制器中的@ModelAttribute方法会在@RequestMapping方法调用之前而调用,示例如下:


1
2
3
4
5
6
7
8
9
10
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}

@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
model.addAttribute(accountManager.findAccount(number));
// add more ...
}
@ModelAttribute方法用来在model中填充属性,如填充下拉列表、宠物类型或检索一个命令对象比如账户(用来在HTML表单上呈现数据)。 @ModelAttribute方法有两种风格:一种是添加隐形属性并返回它。另一种是该方法接受一个模型并添加任意数量的模型属性。用户可以根据自己的需要选择对应的风格。 @ModelAttribute作用在方法参数上 当@ModelAttribute作用在方法参数上时,表明该参数可以在方法模型中检索到。如果该参数不在当前模型中,该参数先被实例化然后添加到模型中。一旦模型中有了该参数,该参数的字段应该填充所有请求参数匹配的名称中。这是Spring

MVC中重要的数据绑定机制,它省去了单独解析每个表单字段的时间。

@ModelAttribute是一种很常见的从数据库中检索属性的方法,它通过@SessionAttributes使用request请求存储。在一些情况下,可以很方便的通过URI模板变量和类型转换器检索属性。

###@Cacheable 和@CacheFlush

• @Cacheable :声明一个方法的返回值应该被缓存。例如:@Cacheable(modelId = "testCaching")
• @CacheFlush :声明一个方法是清空缓存的触发器。例如:@CacheFlush(modelId = "testCaching")
• 说明
 要配合缓存处理器使用,参考: [http://hanqunfeng.iteye.com/blog/603719](http://www.iteye.com/blog/603719)

     spring3.0没有对缓存提供支持,不过3.1之后就有了,可以参考:Spring3.1 Cache注解

###@Resource
• 例如
@Resource
private DataSource dataSource; // inject the bean named ‘dataSource’
• 或者
    @Resource(name=”dataSource”)
    @Resource(type=DataSource.class)
  • 说明
  @Resource 默认按bean 的name 进行查找,如果没有找到会按type 进行查找,
  此时与@Autowired 类 似
  在没有为 @Resource 注解显式指定 name 属性的前提下,如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、  ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。此时 name 属性不需要指定 ( 或者指定为””),否则注入失败;

###@PostConstruct 和@PreDestroy
  • @PostConstruct
在方法上加上注解@PostConstruct ,这个方法就会在Bean 初始化之后被Spring 容器执 行
(注:Bean 初始化包括,实例化Bean ,并装配Bean 的属性(依赖注入))。

  • @PreDestroy
在方法上加上注解@PreDestroy ,这个方法就会在Bean 被销毁前被Spring 容器执行。

###@Repository
• 与@Controller 、@Service 类似,都是向spring 上下文中注册bean ,不在赘述。

###@Component (不推荐使用)
  • @Component
@Component 是所有受Spring 管理组件的通用形式,Spring 还提供了更加细化的注解形式: @Repository 、@Service、@Controller ,它们分别对应存储层Bean ,业务层Bean ,和展示层Bean 。
目前版本(2.5 )中,这些注解与@Component 的语义是一样的,完全通用, 在Spring 以后的版本中可能会给它们追加更多的语义。 所以,我们推荐使用@Repository 、@Service 、@Controller 来替代@Component 。

###@Scope
• 例如
@Scope(“session”)
@Repository()
public class UserSessionBean implementsSerializable {}
• 说明
    在使用XML 定义Bean 时,可以通过bean 的scope 属性来定义一个Bean 的作用范围,
    同样可以通过@Scope 注解来完成
@Scope中可以指定如下值:
singleton:定义bean的范围为每个spring容器一个实例(默认值)
prototype:定义bean可以被多次实例化(使用一次就创建一次)
request:定义bean的范围是http请求(springMVC中有效)
session:定义bean的范围是http会话(springMVC中有效)
global-session:定义bean的范围是全局http会话(portlet中有效)

###@SessionAttributes
  • 说明
  Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,
  以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。
  这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。
  @SessionAttributes 只能声明在类上,而不能声明在方法上。
  • 例如
  @SessionAttributes(“currUser”) // 将ModelMap 中属性名为currUser 的属性
  @SessionAttributes({“attr1”,”attr2”})
  @SessionAttributes(types = User.class)
  @SessionAttributes(types = {User.class,Dept.class})
  @SessionAttributes(types = {User.class,Dept.class},value={“attr1”,”attr2”})

###@InitBinder
  • 说明
  如果希望某个属性编辑器仅作用于特定的 Controller ,
  可以在 Controller 中定义一个标注 @InitBinder 注解的方法,
  可以在该方法中向 Controller 了注册若干个属性编辑器
  • 例如
  @InitBinder
  public void initBinder(WebDataBinder binder) {
  SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd”);
  dateFormat.setLenient(false);
  binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

###@Required
• 例如
@required
public setName(String name){}
• 说明
@ required 负责检查一个bean在初始化时其声明的 set方法是否被执行, 当某个被标注了 @Required 的 Setter 方法没有被调用,则 Spring 在解析的时候会抛出异常,以提醒开发者对相应属性进行设置。 @Required 注解只能标注在 Setter 方法之上。因为依赖注入的本质是检查 Setter 方法是否被调用了,而不是真的去检查属性是否赋值了以及赋了什么样的值。如果将该注解标注在非 setXxxx() 类型的方法则被忽略。

###@Qualifier
• 例如
@Autowired
@Qualifier(“softService”)
private ISoftPMService softPMService;
• 说明
使用@Autowired 时,如果找到多个同一类型的bean,则会抛异常,此时可以使用 @Qualifier(“beanName”),明确指定bean的名称进行注入,此时与 @Resource指定name属性作用相同。

###spring4中提供了大量的注解来支持零配置
@Configuration : 类似于spring配置文件,负责注册bean,对应的提供了@Bean注解。需要org.springframework.web.context.support.AnnotationConfigWebApplicationContext注册到容器中。
@ComponentScan : 注解类查找规则定义
@EnableAspectJAutoProxy : 激活Aspect自动代理
@Import @ImportResource: 关联其它spring配置
@EnableCaching :启用缓存注解
@EnableTransactionManagement : 启用注解式事务管理
@EnableWebMvcSecurity : 启用springSecurity安全验证

###最后放上网友整理的spring注解图

2.1 spring-context模块的注解图


2.2 spring-web注解

2.3 spring其它模块的注解

3

Contents
  1. 1. 1. @Controller
  2. 2. 2. @RequestMapping
  3. 3. 3. @PathVariable
  4. 4. 8. HttpEntity
  5. 5. 9. @ModelAttribute
,